$(document).ready(function(){

    //loadCart();
    loadeadress();
	//返回顶部
	$(window).scroll(function(){
		if($(this).scrollTop()>300){
			$(".fanhui_cou").fadeIn(1500);
			
		}else{
			$(".fanhui_cou").fadeOut(1500);
			
		}
	});
	$(".fanhui_cou").click(function(){
		$("body,html").animate({scrollTop:0},200);
		return false;
	});
	
	//勾选
    $(".checkLabel").click(function(){
    	var flag = $(this).prev().is(':checked');
    	if(flag){
            $(this).prev().attr("checked",false);
            
            $("#buy-sele-all").attr("checked", false); //将全选勾除
            $("#buy-sele-all").val(0);
            
        }else{
        	
            $(this).prev().attr("checked",true);
            
            //如果全部都选中了，将全选勾选
            var groupUL = $(".container").find("ul[class='list-group']").get();
            var checkUL = $(".container").find("div[class='icheck pull-left mr5'] :checkbox:checked").get();
            if(groupUL.length == checkUL.length){
            	$("#buy-sele-all").attr("checked", true);
            	$("#buy-sele-all").val(1);
            }
        }
    	
      //计算总价
	  calculateTotal();
    });
    
    // 全选，全不选
    $("#buy-sele-all").click(function() {
        var flag = $(this).val();

        if(flag ==1){
            $(this).val(0);
             $(".ids").attr("checked", false);
        }else{
            $(this).val(1);
            $(".ids").attr("checked", true);
        }
        
      //计算总价
  	  calculateTotal();
    });
    
	  //计算总价
	 calculateTotal();


    getSrceenWH();

//关闭弹窗
    $('.claseDialogBtn').click(function(){
        $('#dialogBg').fadeOut(300,function(){
            $('#dialog').addClass('bounceOutUp').fadeOut();
        });
    });
});

var w,h,className;
function getSrceenWH(){
    w = $(window).width();
    h = $(window).height();
    $('#dialogBg').width(w).height(h);
}

//相加
function increase(obj){
	var _this = $(obj);
	var _count_obj=_this.prev();
	var count =Number($(_count_obj).val());
	var cartid=$(_count_obj).attr("name");
    var _num=parseInt(count)+1;
	var re = /^[1-9]+[0-9]*]*$/;  
	if( isNaN(_num) || ! re.test(_num)) {
	 	return ;
	}else if(_num==9999){
		return;
	}
	var result = changeShopCartNumber(cartid,1);
	if(result){
		$(_count_obj).val(count*1+1);
		var cash = $(_this).parent().parent().prev().find("em[class='price']").html();//单价
		var total_cash =  $(_this).parent().prev().find("em[class='red productTotalPrice']").html();//商品小计
        var cc=$(_count_obj).val();
		var e_cash = Number(cc)*Number(cash);
		$(_this).parent().prev().find("em").html("¥"+e_cash);
		
		//计算总价
		calculateTotal();
	}
	
}

//减
function disDe(obj){
	var _this = $(obj);
	var _count_obj=_this.next();
	var count =Number($(_count_obj).val());
    var cartid=$(_count_obj).attr("name");
	var _num=parseInt(count)-1;

	var re = /^[1-9]+[0-9]*]*$/;
	if( isNaN(_num) || ! re.test(_num)) {
	 	return ;
	}else if(_num==0){
		return ;
	}
	var result = changeShopCartNumber(cartid,-1);
	if(result){
		$(_count_obj).val(count*1-1);
		var cash = $(_this).parent().parent().prev().find("em[class='price']").html();//单价
		var total_cash =  $(_this).parent().prev().find("em[class='red productTotalPrice']").html();//商品小计
        var cc=$(_count_obj).val();
        var e_cash = Number(cc)*Number(cash);
		$(_this).parent().prev().find("em").html("¥"+e_cash);
		
		//计算总价
		calculateTotal();
	}
}
//更新购物车商品数量
function changeShopCartNumber(cartid,count){
	var config = false;
	$.ajax({
		url: "/mall/newOrder/updateshortcount.do",
		data: {"cartid":cartid,"count":count},
		type:'post', 
		async : false, //默认为true 异步   
		dataType : 'json', 
		error:function(data){
		},  
		success:function(result){
			if(result.data==1){
				config = true;
			}else {
				floatNotify.simple("参数有误");
			}
		}
	});
	return config;
}

//计算总价
function calculateTotal(){
	var allCash = 0;
	var list = $(".container").find("ul[class='list-group']").get();
	for(var i=0;i<list.length;i++){
		var selected = $(list[i]).find("div[class='icheck pull-left mr5']>:checkbox").is(":checked");
		if(selected){
			var cash = $(list[i]).find("em[class='price']").html();//取单价
			var count = $(list[i]).find("input[class='btn gary2 Amount']").val();//取数量
			allCash += Number(cash)*Number(count);
		}
	}
	
	allCash = Math.round(Number(allCash)*100)/100;
	var pos_decimal = allCash.toString().indexOf('.');
	if (pos_decimal < 0)
	{
		allCash += '.00';
	}
	$("#totalPrice").html(allCash);
}

//删除购物车商品
function deleteShopCart(id){

    var shopcartid=id;
	if(confirm("删除后不可恢复, 确定要删除吗？")){
		$.ajax({
			url: "/mall/newOrder/shortdelete.do",
			data: {"shopcartid":shopcartid},
			type:'post', 
			async : true, //默认为true 异步

			dataType : 'json', 
			error:function(data){
			},   
			success:function(data){
				if(data.data==1){
					window.location.href= "/mall/newOrder/shopcart.html";
					return ;
				}else{
					floatNotify.simple("删除失败");
					return false;
				}
				
			}   
		});         
	} 
}
//加载收货地址
function loadeadress() {
var userid=$("#userid").val();
    $.get("/mall/newOrder/loadeadress.do?userid="+userid, function (data) {
        if (data.state == 0) {
            $("#adressinfo").html("");
            var cat="";
            var list = $("#adressinfo");
            var nn=0;
            $(data.data).each(function (index, item) {
                nn++;
                if(index==0){
                    cat += '<li>' +
                        '<label>' +
                        '<input type="radio" name="dizhi" checked class="idsw"   dizhi="'+item.address+'" addressid="'+item.id+'"/> ' +
                        '<input type="text" name="address" required value="'+item.address+'" class="ipt" /></label></li>';
                }else{
                    cat += '<li>' +
                        '<label>' +
                        '<input type="radio" name="dizhi" class="idsw"   dizhi="'+item.address+'" addressid="'+item.id+'"/> ' +
                        '<input type="text" name="address" required value="'+item.address+'" class="ipt" /></label></li>';
				}
            });
            if(nn<3) {
                cat += '<li>' +
                    '<label>' +
                    '<input type="radio" name="dizhi" class="idsw"  dizhi="" addressid=""/> ' +
                    '<input type="text" name="address" required value="" class="ipt" id="xindizhi" placeholder="在这里输入新地址和电话"/>' +
                    '</label>' +
                    '</li>'
            }
            cat=cat+ '<li><input type="button" value="确认提交" class="submitBtn" onclick="addaddress()"/></li>';
            list.html(cat);
        } else {
            alert(data.message);
        }
    });
}


function submitShopCart(){
         //显示弹框
        className = "bounceIn";
        $('#dialogBg').fadeIn(300);
        $('#dialog').removeAttr('class').addClass('animated '+className+'').fadeIn();
}

function addaddress() {
    var addressss = [];
    $("input[name='address']").each(function () {
        if ($(this).val() != undefined && $(this).val() != '') {
            addressss.push($(this).val());
        }
    });
    $.ajax({
        url: "/mall/newOrder/updateadress.do",
        data: {"addressss": addressss.join(",")},
        type: 'post',
        async: true, //默认为true 异步
        dataType: 'json',
        error: function (data) {
        },
        success: function (data) {
            if (data.data != 1) {
                alert("系统异常");
                return;
            } else {
                addorder();
            }
        }
    });
}

function addorder(){
	var array = $(".ids:checked").get();
	if(array.length==0){
		floatNotify.simple("请选择要结算的商品");
		return;
	}
    var shopCartStr = "";
	for(var i in array){
		var short_id = $(array[i]).attr("itemkey");
		shopCartStr=shopCartStr + short_id+",";
	}
    shopCartStr=shopCartStr.substr(0,shopCartStr.length-1);
    var dizhi = $('input[name="dizhi"]:checked').attr("dizhi");
    var totalPrice = $("#totalPrice").text();
    $.ajax({
        url: "/mall/newOrder/addOrder.do",
        data: {
        	"shopCartStr": shopCartStr,
            "dizhi":dizhi,
            "totalPrice":totalPrice
		},
        type: 'post',
        async: true,
        dataType: 'json',
        error: function (data) {
        },
        success: function (data) {
            if (data.data<1) {
                alert("系统异常");
                return;
            } else {
                $('#dialogBg').fadeOut(300,function(){
                    $('#dialog').addClass('bounceOutUp').fadeOut();
                });
                window.location.href= "/mall/newOrder/payment.html?shortid="+data.data;
            }
        }
    });



}

function abstractForm(URL, shopCartIds){
	   var temp = document.createElement("form");        
	   temp.action = URL;        
	   temp.method = "post";        
	   temp.style.display = "none";        
	   var opt = document.createElement("textarea");        
	   opt.name = 'shopCartItems';        
	   opt.value = shopCartIds;        
	   temp.appendChild(opt);        
	   document.body.appendChild(temp);        
	   temp.submit();        
	   return temp;  
}

//加载购物车
/*
function loadCart() {
    $.get("/mall/newOrder/listCart.do", function (data) {
        if (data.state == 0) {
           // $("#shopcartid").html("");
            var list = $("#shopcartid");
            if (data.data.length <= 0) {
                alert("您的购物车中暂无商品，快去购物吧！");
                return;
            }
            $(data.data).each(function (index, item) {
                var cat = $('<ul class="list-group"></ul>');
                var cat1 = $('<li class="list-group-item text-primary"><div class="icheck pull-left mr5"><input type="checkbox" checked="checked" class="ids" prodStatus="1"  itemkey=""/><label class="checkLabel"><span></span></label></div>朗尊软件</li>');
                var cat2 = $('<li class="list-group-item hproduct clearfix"><div class="p-pic"><a href="/views/663"><img class="img-responsive" src="img/1787bd1d-9381-402b-b98e-97ceeddf7692.jpg"></a></div><div class="p-info"> <a href="/views/663"><p class="p-title">艾吉贝2015新款多层收纳真皮单肩斜挎包女包头层牛皮斜跨小包包女</p></a> <p class="p-attr"> <span>颜色：红色；</span></p> <p class="p-origin"> <a class="close p-close" onclick="deleteShopCart(\'\',\'艾吉贝2015新款多层收纳真皮单肩斜挎包女包头层牛皮斜跨小包包女\',\'663\',\'1358\')" href="javascript:void(0);">×</a> <em class="price">¥179.00</em> </p> </div></li>');
                var cat3 = $('<li class="list-group-item clearfix"> <div class="pull-left mt5"> <span class="gary">小计：</span> <em class="red productTotalPrice">¥179.00</em> </div> <div class="btn-group btn-group-sm control-num"> <a onclick="disDe(this)" href="javascript:void(0);" class="btn btn-default"><span class="glyphicon glyphicon-minus gary"></span></a> <input type="tel" class="btn gary2 Amount" readonly="readonly" value="1" maxlength="4" itemkey="" prodId="663" skuId="1358"> <a onclick="increase(this)" href="javascript:void(0);" class="btn btn-default"><span class="glyphicon glyphicon-plus gary"></span></a> </div> </li>');
                cat.append(cat1);
                cat.append(cat2);
                cat.append(cat3);
                list.append(cat);
            });
        } else {
            layer.msg(data.message);
        }
    });
}*/
